P(APP_PATH + getUrl('/public/nav'))			
app
.directive("nav",function(){

  return {
    restrict: "A",
	priority: 800,
    replace: true,
    templateUrl: APP_PATH + getUrl('/public/nav')
  };
})
.directive("sidebar",function($http,$location){

  return {
    restrict: "A",
	priority: 799,
    replace: true,
    templateUrl: APP_PATH + getUrl('/public/sidebar'),
    link: function(scope){
      scope.menu = {};
      $http.get(APP_PATH + getUrl('/public/jsonMenu')).success(function(data){
        scope.menu.list = data;
      });
    }
  };
})
.directive("error",function($rootScope){
  return {
    restrict: "E",
    template: '<div class="alert-box alert" ng-show="isError">Error!!!</div>',
    link: function(scope){
      $rootScope.$on("$routeChangeError",function(event,current,previous,rejection){
        scope.isError = true;
      });
    }
  };
})
.directive("switchBool",function(){
	return {
		restrict: "A",
		link: function(scope,element,attrs){
			//为了兼容ng与浏览器，_id取名mgid
			var _id = null;		//表中的_id
			var collection = element.parents("table").attr("collection");
			var line = element.parents("table").attr("line");	//循环变量对象
			var field = attrs["switchBool"];	//得到字段名
			line = line ? line : "line";
			element.bind("click",function(){
				_id = _id ? _id : element.parents("tr").attr("mgid"); //只取一次_id
				if ( _id && collection && field) {	//三者都有效时，才执行
					scope.$apply( function(){
						scope.db.switchBool(collection,_id,field);
						if ( field.match('[.]') ) {
							var arr = field.split('.');
							var first = null;
							var last = arr.pop();
							var obj = scope[line];
							while( arr.length>0 ) {
								first = arr.shift(arr);
								if ( obj[first] === undefined ) {
									obj[first] = {};									
								}
								obj = obj[first];
							}
							if ( obj[last] === undefined ) {
								obj[last] = false;
							}							
							if ( typeof obj[last] !== 'boolean' ) {
								obj[last] = parseInt(obj[last]);
							}
							obj[last] = !obj[last];
						} else {
							if ( typeof scope[line][field] !== 'boolean' ) {
								scope[line][field] = parseInt(scope[line][field]);
							}						
							scope[line][field] = !scope[line][field];
						}						
					});
				} else {
					console.devBug();
				}
			});
		}
	};
} )
.directive("loadById",function(){
	return {		
		restrict: "A",
		link: function(scope,element,attrs){			
			//为了兼容ng与浏览器，_id取名mgid
			var _id = null;		//表中的_id
			var collection = element.parents("table").attr("collection");
			var line = element.parents("table").attr("line");	//循环变量对象
			var field = attrs["loadById"];	//得到字段名
			line = line ? line : "line";
			element.bind("click",function(){				
				_id = _id ? _id : element.parents("tr").attr("mgid");
				if ( scope[line][field] === undefined ) {
					scope.db.findFieldsById(collection,_id,field).success(function(data){
						var type = typeof data ;
						if (  type == 'object' ) {
							scope[line][field] = data[field];
						} else if ( type == 'string' ) {
							scope[line][field] = data;
						}
						if ( scope[line][field] !== undefined ) {						
							angular.element("#" + scope.modal).modal('toggle').find('.modal-body').html(scope[line][field]).end().find('h2').html('ID:' + _id + '　“'+ scope[line]['title'] + '”');
						}
					} );
				} else {
					angular.element("#" + scope.modal).modal('toggle').find('.modal-body').html(scope[line][field]).end().find('h2').html('ID:' + _id + '　“'+ scope[line]['title'] + '”');
				}
			});
		}
	};
} )
.directive("postStar",function(){
	return {
		restrict: "A",
		link: function(scope,element,attrs){
			var _id = null;		//表中的_id
			var collection = element.parents("table").attr("collection");
			var line = element.parents("table").attr("line");	//循环变量对象
			var createDom = function ( elem,i,type) {
				var dom = angular.element('<i class="fa fa-star star-' + type+ '" title="置顶为' + i +'星级" is-top="'+ i +'"></i>').bind("click", i,function(event){
					var value = angular.element(event.target).attr('is-top');
					_id = _id ? _id : element.parents("tr").attr("mgid");
					value = parseInt(value);
					scope[line].is_top = value;
					scope.db.modifyById(collection,{'is_top':value},_id).success(function(){
						elem.empty();
						for (var i=1;i<=value;i++ ) {				
							createDom(elem,i,'gold');
						}
						for ( ; i<=5; i++ ) {
							createDom(elem,i,'muted');
						}
					});
				} );
				elem.append(dom);		
			}			
			
			var starValue = parseInt( attrs['postStar'] );
			
			if ( isNaN(starValue) ){
				starValue = 0;
			}
			var i=1
			
			for ( ;i<=starValue;i++ ) {				
				createDom(element,i,'gold');
			}
			for ( ; i<=5; i++ ) {
				createDom(element,i,'muted');
			}
			
		}
	};
} )
.directive("setTop",function(){
	return {
		restrict: "A",
		link: function(scope,element,attrs){
			var table = attrs['tableName'];
			var createDom = function ( elem,i,type) {
				var dom = angular.element('<i style="width:20px;" class="fa fa-star star-' + type+ '" title="置顶为' + i +'星级" is-top="'+ i +'"></i>').bind("click", i,function(event){
					var value = angular.element(event.target).attr('is-top');
					value = parseInt(value);
					if ( scope[table]===undefined ) {
						scope[table] = {};
					}
					scope[table].is_top = value;
					elem.empty();
					for (var i=1;i<=value;i++ ) {				
						createDom(elem,i,'gold');
					}
					for ( ; i<=5; i++ ) {
						createDom(elem,i,'muted');
					}
				} );
				elem.append(dom);		
			}

			var starValue = parseInt( attrs['setTop'] );
			
			if ( isNaN(starValue) ){
				starValue = 0;
			}
			var i=1
			
			for ( ;i<=starValue;i++ ) {				
				createDom(element,i,'gold');
			}
			for ( ; i<=5; i++ ) {
				createDom(element,i,'muted');
			}
			
		}
	};
} )
.directive("switchSomeBool",function($timeout){
	return {
		restrict: "A",
		link: function(scope,element,attrs){
			//为了兼容ng与浏览器，_id取名mgid
			var _id = null;		//表中的_id
			var collection = element.parents("table").attr("collection");
			var fields = attrs["switchSomeBool"].split(":");	//得到字段名
			var bool = fields[1] == 'true' ? true : false;
			var field = fields[0];
			
			element.bind("click",function(){
				
				var ids = element.parents("table").find("tr").has("input:first:checked").map(function(){
					return angular.element(this).attr('mgid');
				}).get();
				var data = {};
				data[field] = bool
				if ( ids.length) {
					scope.db.modifyByIds(collection,ids,data);
					scope.data.forEach(function(item){
						if (ids.indexOf( item["_id"].toString() )!=-1) {
							item[field] = bool;															
						}
					});						
				} else {
					scope.error({info:'你未选中任何行！'});
				}
			});
		}
	};
} )
.directive('changeById',function($timeout){
	return {
		restrict: 'A',
		link: function( scope,element,attrs ){
			//为了兼容ng与浏览器，_id取名mgid
			var _id = null;		//表中的_id
			var collection = element.parents("table").attr("collection");
			var field = attrs["changeById"];	//得到字段名
			var value = null;
			var line = element.parents("table").attr("line");	//循环变量对象
			line = line ? line : "line";
			element.bind("change",function(){				
				$timeout( function( ) {
					_id = _id ? _id : element.parents("tr").attr("mgid");
					value = element.val();	
					if ( _id && collection ) {	//两者都有效时，才执行
						var data = {};
						data[field] = value;
						
						scope.db.modifyById(collection,data,_id).success(function(){
								if ( scope.render ) {
									scope.render( function(x,y){
											return parseInt(x[field]) - parseInt(y[field]);
									} );
								}
								
								if ( collection == 'category' ) {
									scope.data.sort( function(x,y){
										return parseInt(x[field]) - parseInt(y[field]);
									} );
								}
						});
					}

				} , 300 );
			});
		}
	};

} )
.directive('removeById',function(){
	return {
		restrict: 'A',
		link: function( scope,element,attrs ){
			//为了兼容ng与浏览器，_id取名mgid
			var _id = null;	//表中的_id
			var collection = element.parents("table").attr("collection"); //表名
			var line = element.parents("table").attr("line");	//循环变量对象
			line = line ? line : "line";	//取不到时，默认取"line"
			element.bind("click",function(){
				_id = _id ? _id : element.parents("tr").attr("mgid");
				if ( _id && collection ) {	//两者都有效时，才执行				
					swal(
						{   
							title: "你确定要删除数据吗?",   
							text: "删除数据后，将无法恢复！",   
							type: "warning",   
							showCancelButton: true,
							cancelButtonText: '取消',
							confirmButtonColor: "#DD6B55",   
							confirmButtonText: "删除",   
							closeOnConfirm: false,
							showLoaderOnConfirm: true
						}, 
						function() {  
							scope.$apply( function(){
								scope.db.removeById(collection,_id).success(function(){
									scope[line] = null;
									swal({   
										title: "从数据库中成功删除!",   
										text: "2 秒后自动关闭", 
										type: 'success',
										timer: 2000,   
										showConfirmButton: false 
									});
									if ( scope.render ) {
										scope.render();
									}
									
								});
								
							} );							
						});	
				} else {
					console.devBug();
				}
			});
		}
	};

} )
.directive("switchById",function(){
	return {
		restrict: 'A',
		link: function( scope,element,attrs ){
			//为了兼容ng与浏览器，_id取名mgid
			var _id = null;		//表中的_id
			var collection = element.parents("table").attr("collection");
			var line = element.parents("table").attr("line");	//循环变量对象
			var field = attrs["switchById"];	//得到字段名
			line = line ? line : "line";
			element.bind("click",function(){
				_id = _id ? _id : element.parents("tr").attr("mgid");
				if ( _id && collection ) {	//两者都有效时，才执行				
					scope.$apply( function(){
						scope.db.switchBool(collection,_id,field,function(){
							scope[line] = null;
							swal({   
								title: "修改成功",   
								text: "2 秒后自动关闭", 
								type: 'success',
								timer: 2000,   
								showConfirmButton: false 
							});
							if ( scope.render ) {
								scope.render();
							}							
						} );
						
					} );	
				} else {
					console.devBug();
				}
			});
		}
	};
} )
.directive("toggle", function(){
	return {
		restrict: "A",
		link: function(scope,element,attrs) {
			attr = attrs['toggle'];
			if ( attr == 'tooltip' ) {
				element.tooltip({html:true});
			} else if ( attr == 'popover' ) {
				element.popover().click(function(e){
					e.preventDefault();
				});				
			}
			
		}
	};
} )

/*
	<edit>加载modal模态框</edit>
*/
.directive('categoryEdit',function(){	
	return {
		restrict: 'E',
		templateUrl: '/' + _ADMIN_NAME + '/' + document.querySelector("table[collection]").getAttribute("collection") + '/edit'
	};

} )
.directive('linkEdit',function(){
	return {
		restrict: 'E',
		templateUrl:  APP_PATH + '/' + document.querySelector("table[collection]").getAttribute("collection") + '/edit'
	};

} )
.directive('fieldView',function(){
	return {
		restrict: 'E',
		templateUrl:  APP_PATH + getUrl(document.querySelector("table[collection]").getAttribute("collection") + '/field') 
	};

} )
.directive('albumEdit2',function(){
	return {
		restrict: 'E',
		templateUrl: '/' + _ADMIN_NAME + '/' + document.querySelector("table[collection]").getAttribute("collection") + '/edit'
	};

} )
/*
	<button edit-by-id>编辑</button>
	编辑表格中的每一行
*/
.directive('editLinkById',function($templateCache){
	return {
		restrict: 'A',
		link: function( scope,element,attrs ){
			var line = element.parents("table").attr("line");	//循环变量对象
			line = line ? line : "line";	//取不到时，默认取"line"
			element.bind("click",function(){
				scope[line].expire_time = scope[line].expire_time.slice(0,10);
				angular.element('#' + scope.editModal).modal('toggle');
				scope.$parent.$apply( function(){
					scope.$parent._editScope = scope;
					scope.$parent[line] = angular.copy(scope[line]);
				} );				
			});
		}
	};

} )
/*
	<button edit-by-id>编辑</button>
	编辑表格中的每一行
*/
.directive('editById',function($templateCache){
	return {
		restrict: 'A',
		link: function( scope,element,attrs ){
			var line = element.parents("table").attr("line");	//循环变量对象
			line = line ? line : "line";	//取不到时，默认取"line"
			element.bind("click",function(){
				console.log(scope.showFileInput);
				angular.element('#' + scope.editModal).modal('toggle');
				scope.$parent.$apply( function(){
					scope.$parent._editScope = scope;
					scope.$parent[line] = angular.copy(scope[line]);
				} );				
			});
		}
	};

} )
/*
	<form link-edit-form></form>
	表修友情链接的表单
*/
.directive("linkEditForm",function($rootScope){
	var line = document.querySelector("table[collection]").getAttribute("line");
	line = line ? line : "line";	//取不到时，默认取"line"
	var oEditModal = null;
	return {
		//此时的scope对应的是 LinkCtrl的$scope
		link: function(scope,element,attrs){
			element.find(".btn-cancel").bind("click",function(){	//取消按钮
				oEditModal = oEditModal || angular.element('#' + scope.editModal);
				oEditModal.modal('toggle');
			});
			
			element.bind("submit",function(form){
				oEditModal = oEditModal || angular.element('#' + scope.editModal);
				scope.update(scope[line]);
				scope._editScope[line] = scope[line];

				btnEdit = angular.element("table tr[mgid=" + scope._editScope[line]._id + "] .btn-edit");
				btnEdit.removeClass('btn-primary btn-warning btn-success').addClass("btn-success");
				oEditModal.modal('toggle');
			});
		}
	};
})
.directive("AlbumEditForm1",function($rootScope, ngDialog){
	var line = document.querySelector("table[collection]").getAttribute("line"); //--
	line = line ? line : "line";	//--取不到时，默认取"line"
	var oEditModal = null;	//--
	return {
		//--此时的scope对应的是 LinkCtrl的$scope
		link: function(scope,element,attrs){	//--
			element.find(".btn-cancel").bind("click",function(){	//--取消按钮
				oEditModal = oEditModal || angular.element('#' + scope.editModal); //--
				oEditModal.modal('toggle');	//--
			});	//--
			
			element.bind("submit",function(form){
				oEditModal = oEditModal || angular.element('#' + scope.editModal);
				
				scope.update(scope[line]);
				scope._editScope[line] = scope[line];

				btnEdit = angular.element("table tr[mgid=" + scope._editScope[line]._id + "] .btn-edit");
				btnEdit.removeClass('btn-primary btn-warning btn-success').addClass("btn-success");
				oEditModal.modal('toggle');
			});
		}
	};
})
.directive("categoryEditForm2",function($rootScope, ngDialog){
	var line = document.querySelector("table[collection]").getAttribute("line");
	line = line ? line : "line";	//取不到时，默认取"line"
	var oEditModal = null;
	return {
		//此时的scope对应的是 LinkCtrl的$scope
		link: function(scope,element,attrs){
			element.find(".btn-cancel").bind("click",function(){	//取消按钮
				oEditModal = oEditModal || angular.element('#' + scope.editModal);
				oEditModal.modal('toggle');
			});
			
			element.bind("submit",function(form){
				oEditModal = oEditModal || angular.element('#' + scope.editModal);
				scope.update(scope[line]);
				scope._editScope[line] = scope[line];

				btnEdit = angular.element("table tr[mgid=" + scope._editScope[line]._id + "] .btn-edit");
				btnEdit.removeClass('btn-primary btn-warning btn-success').addClass("btn-success");
				oEditModal.modal('toggle');
			});
		}
	};
})
.directive("linkEditForm2",function($rootScope, ngDialog){
	var btnCancel = null;
	var tr = null;
	var btnEdit = null;
	return {
		link: function(scope,element,attrs){
			element.find(".btn-cancel").bind("click",function(){	//取消按钮
				//var new_time = element.find("#expire_time").val() ;
				//scope.link.expire_time = new_time;
				//if (attrs.linkEditForm=="true" || new_time != scope.link.expire_time){
					//scope.link.expire_time = new_time;
					//btnEdit =element.parents("body").find("table tr[mgid=" + scope.link._id + "] .btn-edit");
					//btnEdit.removeClass('btn-primary btn-warning btn-success').addClass("btn-warning");
				//}
				scope.$apply(function(){
					for(var key in $rootScope.link){
						scope.link[key] = $rootScope.link[key];
					}
				});

				ngDialog.close();
			});

			element.bind("submit",function(form){
				var new_time = element.find("#expire_time").val() ;
				scope.link.expire_time = new_time ;
				scope.update(scope.link);

				btnEdit = angular.element("table tr[mgid=" + scope.link._id + "] .btn-edit");
				btnEdit.removeClass('btn-primary btn-warning btn-success').addClass("btn-success");
				ngDialog.close();
			});
		}
	};
})
.directive("albumEditForm3",function($rootScope, ngDialog,$http){
	var btnCancel = null;
	var tr = null;
	var btnEdit = null;
	return {
		link: function(scope,element,attrs){
			element.find(".btn-cancel").bind("click",function(){	//取消按钮
				scope.$apply(function(){
					for(var key in $rootScope.album){
						scope.album[key] = $rootScope.album[key];
					}
				});

				ngDialog.close();
			});

			element.bind("submit",function(form){
				scope.setFile(scope,scope.album);
				scope.db.updateById('album',scope.album,function(){
					//获取缩略图的img
					var img = angular.element("table tr[mgid=" + scope.album._id + "] img[src*='upload']");
					scope.changeBase64(img,scope.album.base64);
				} );

				btnEdit =angular.element("table tr[mgid=" + scope.album._id + "] .btn-edit");
				btnEdit.removeClass('btn-primary btn-warning btn-success').addClass("btn-success");
				ngDialog.close();
			});
		}
	};
})
.directive('fileModel', function ($parse) {
	return {
		restrict: 'A',
		link: function(scope, element, attrs, ngModel) {
			var model = $parse(attrs.fileModel);
			var modelSetter = model.assign;
			element.bind('change', function(event){
				scope.$apply(function(){
					modelSetter(scope, element[0].files[0]);
				});
				//附件预览
				scope.file = (event.srcElement || event.target).files[0];
				scope.getFile();
			});
		}
	};
})
.directive("pageList",function(){
	return {
		restrict: "A",
		link: function(scope,element,attrs){
			element.bind("click",function(){
				var page = parseInt(attrs.pageList);
				if ( page!=scope.pageList.page ) {					
					scope.changePage(page);					
				}				
			});
			/*
			var collection = element.parents("table").attr("collection"); //表名
			element.bind("click",function(){			
				scope.pageList.page = parseInt(attrs.pageList);	
				scope.pageList.list();
				scope.db.find(collection ,{options:{sort:scope.sort,skip:scope.pageList.skip,limit:scope.pageList.perpage}}  , function(data){
					scope.data = data;	
				} );				
			} );
			*/
		}
	};
} )
.directive("datePicker", function(){
	return function(scope,element,attrs){
		element.bind("blur",function()
		{
			var value = element.val();
			if ( value ) {
				var str = 'scope.' + attrs['datePicker'] + '="' + element.val() + '";';
				eval(str);
			}
		});
	}
} )
.directive('multipleEmail', [function ()
{	//验证多个邮箱
  return {
		require: "ngModel",
		link: function (scope, element, attr, ngModel) {
			if (ngModel) {
				//var emailsRegexp = /^([a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*[;；]?)+$/i;
			}
			var customValidator = function (value) {
			var validity = ngModel.$isEmpty(value) || emailsRegexp.test(value);
				ngModel.$setValidity("multipleEmail", validity);
			return validity ? value : undefined;
			};
			ngModel.$formatters.push(customValidator);
			ngModel.$parsers.push(customValidator);
		}
	};
}]);